<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :init-param="initParam">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="batchInit"> 批量初始化 </el-button>
        <el-button :icon="CirclePlus" @click="importLastMonth"> 引入上月 </el-button>
        <el-button :icon="CirclePlus" @click="openDrawer('新增')"> 新增 </el-button>
        <el-button :icon="CirclePlus" @click="openDrawer('新增跨组')"> 新增跨组 </el-button>
      </template>
      <template #orgId="scope">
        <span>{{ orgRender(scope, orgList) }}</span>
      </template>
      <template #avgScore="scope">
        <el-input-number
          style="width: 100%"
          :min="0"
          :max="2"
          :step="0.1"
          :precision="1"
          v-model="scope.row.avgScore"
          @change="onScoreChange(scope.row)"
        ></el-input-number>
      </template>
      <template #level="scope">
        <!-- <el-button type="primary" link @click="openDrawer('编辑', scope.row)"> {{ scope.row.level }} </el-button> -->
        <common-select
          data-key="PERFORMANCE_LEVEL"
          :request-api="() => apiService.findClassify('PERFORMANCE_LEVEL')"
          v-model="scope.row.level"
          @change="onLevelChange(scope.row)"
        ></common-select>
      </template>
      <template #chat_state="scope">
        <el-switch
          :key="scope.row._id"
          v-model="scope.row.chat_state"
          active-value="1"
          inactive-value="0"
          @change="onChatStateChange(scope.row)"
        ></el-switch>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑 </el-button>
        <el-button v-if="scope.row.state === '0'" type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">
          删除
        </el-button>
      </template>
    </ProTable>
    <EvaluateDrawer ref="drawerRef" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, computed, onMounted } from "vue";
import { Performance } from "@/api/types/base";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import EvaluateDrawer from "./evaluateDrawer.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { EditPen, View, Delete, CirclePlus } from "@element-plus/icons-vue";
import apiService from "@/api/services/apiService";
import commonSelect from "@/components/SelectFilter/common-select.vue";
import { enumRender, monthRender, userRender, orgRender } from "@/hooks/useColumnRender";
import { useUserStore } from "@/stores/modules/user";
import { useDataStore } from "@/stores/modules/data";
import { ElMessage, ElMessageBox } from "element-plus";
import { Md5 } from "ts-md5";

const initVar = reactive({
  tbName: "performance",
  tbCnName: "绩效评估"
});

// const defaultOrgId = ref();
const defaultDate = ref<Date>();
let curDate = new Date();
let [year, month] = [curDate.getFullYear(), curDate.getMonth()];
defaultDate.value = new Date(year, month - 1, 1);

// ProTable 实例
const proTable = ref<ProTableInstance>();
const userUser = useUserStore();
const dataStore = useDataStore();

const paramKey = ref();
const orgSelectList = computed(() => dataStore.getCommonDataByName(paramKey.value));
const orgList = computed(() => dataStore.orgList);
const isOrNotList = computed(() => dataStore.getEnumByCsName("IS_NOT"));
const userList = computed(() => dataStore.userList);
onMounted(async () => {
  dataStore.findUserList();
  dataStore.findEnumByCsName("IS_NOT");
  dataStore.findOrgList();
  // let params = {
  //   condition: {
  //     $or: [{ leader: userUser.userInfo._id }, { superVisor: userUser.userInfo._id }, { assistantManage: userUser.userInfo._id }],
  //     leaf: "1"
  //   },
  //   options: { sort: { sort: 1 } }
  // };
  // paramKey.value = Md5.hashStr(JSON.stringify(params));
  // let data = await dataStore.findList(paramKey.value, () => apiService.find("orgs", params.condition, params.options));
  // if (data && data.length > 0) {
  //   const org = data.find(org => org.leader === userUser.userInfo._id);
  //   if (org) {
  //     defaultOrgId.value = org._id;
  //   } else {
  //     defaultOrgId.value = data[0]._id;
  //   }

  //   if (columns[2].search) {
  //     columns[2].search["defaultValue"] = defaultOrgId.value;
  //     proTable.value?.setInitSearch();
  //     proTable.value?.search();
  //   }
  // }
});

const initParam = reactive({
  condition: { chargeUser: userUser.userInfo._id },
  options: { sort: { avgScore: -1, level: 1 } }
});

const getTableList = async (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  if (newParams.condition && newParams.condition.performanceDate) {
    let curDate = new Date(newParams.condition.performanceDate);
    let [year, month] = [curDate.getFullYear(), curDate.getMonth()];
    let startDate = new Date(year, month, 1);
    let endDate = new Date(year, month + 1, 0, 23, 59, 59);
    newParams.condition.performanceDate = { $gte: startDate, $lte: endDate };
  }
  return apiService.findPage(initVar.tbName, newParams.condition, newParams.options);
};

// 表格配置项
const columns = reactive<ColumnProps<Performance>[]>([
  { type: "index", label: "序号", width: 85 },
  { prop: "userId", label: "姓名", width: 100, render: scope => userRender(scope, userList) },
  {
    prop: "orgId",
    label: "组织",
    width: 160,
    fieldNames: { label: "name", value: "_id" },
    // search: { el: "select", props: { clearabled: true }, order: 2 },
    enum: orgSelectList
  },
  {
    prop: "performanceType",
    label: "评估类型",
    search: { el: "select", props: { filterable: true } },
    enum: () => apiService.findClassify("performanceType"),
    fieldNames: { label: "name", value: "value" }
  },
  {
    prop: "performanceDate",
    label: "绩效周期",
    render: monthRender,
    search: {
      el: "date-picker",
      props: { type: "month" },
      order: 1,
      defaultValue: defaultDate,
      label: "绩效周期"
    }
  },
  {
    prop: "crossGroup",
    label: "跨组",
    search: { el: "select", props: { filterable: true } },
    enum: isOrNotList,
    render: scope => enumRender(scope, isOrNotList, "value"),
    fieldNames: { label: "name", value: "value" }
  },
  {
    prop: "crossRate",
    label: "评估占比",
    enum: () => apiService.findClassify("crossRate"),
    fieldNames: { label: "name", value: "value" }
  },
  {
    prop: "level",
    label: "等级",
    width: 140,
    enum: () => apiService.findClassify("PERFORMANCE_LEVEL"),
    fieldNames: { label: "name", value: "value" }
  },
  { prop: "avgScore", label: "综合评分", width: 140 },
  {
    prop: "chat_state",
    label: "是否面谈",
    enum: isOrNotList,
    fieldNames: { label: "name", value: "value" }
  },
  {
    prop: "state",
    label: "个人查看",
    enum: isOrNotList,
    search: { el: "select", props: { filterable: true } },
    render: scope => enumRender(scope, isOrNotList, "value"),
    fieldNames: { label: "name", value: "value" }
  },
  { prop: "operation", label: "操作", align: "left", fixed: "right", width: 240 }
]);

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof EvaluateDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<Performance> = {}) => {
  const params = {
    title,
    tbName: initVar.tbName,
    isView: title === "查看",
    row: row,
    api: title.indexOf("新增") !== -1 ? apiService.save : title === "编辑" ? apiService.updateById : undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};

// 删除信息
const deleteAccount = async (params: Performance) => {
  await useHandleData(apiService.deleteById, initVar.tbName, params._id, `删除`);
  proTable.value?.getTableList();
};

// 检查用户是否重复
const checkRepeat = (userId: string) => {
  let result = false;
  if (userId) {
    proTable.value?.tableData.forEach(item => {
      if (item.userId === userId) {
        result = true;
      }
    });
  }
  return result;
};

// 批量初始化
const initParamKey = ref();
const batchInit = async () => {
  let params = {
    condition: {
      $or: [{ manage_user_performance_main: userUser.userInfo._id }, { manage_user_performance_sub: userUser.userInfo._id }]
    }
  };
  initParamKey.value = Md5.hashStr(JSON.stringify(params));
  let data = await dataStore.findList(initParamKey.value, () => apiService.find("manage_user", params.condition));
  if (data && data.length > 0) {
    ElMessageBox.confirm(`有【${data.length}】位员工待绩效评估，是否初始化?`, "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "info",
      draggable: true
    }).then(() => {
      data.forEach(async user => {
        let item: Partial<Performance> = {};

        let curDate = new Date(proTable.value?.searchParam.performanceDate);
        let [year, month] = [curDate.getFullYear(), curDate.getMonth()];
        let defaultDate = new Date(year, month, 1);
        // 默认上个月
        item.performanceDate = defaultDate;
        item.orgId = user.orgId;
        item.state = "0";
        item.create_at = new Date();
        item.create_user = userUser.userInfo._id;
        item.chargeUser = userUser.userInfo._id;
        item.chargeUserName = userUser.userInfo.userName;
        item.avgScore = 1.0;
        item.performanceType = "1";
        item.level = "B";
        item.chat_state = "0";
        item.userId = user.userId;
        item.userName = user.userName;
        if (userUser.userInfo._id === user.manage_user_performance_main) {
          item.crossGroup = "0";
          item.crossRate = user.crossRate_main;
        } else if (userUser.userInfo._id === user.manage_user_performance_sub) {
          item.crossGroup = "1";
          item.crossRate = user.crossRate_sub;
        }
        if (item.userId && !checkRepeat(item.userId)) {
          await apiService.save(initVar.tbName, item);
        }
      });
      ElMessage({
        type: "success",
        message: `初始成功!`
      });
      setTimeout(() => {
        proTable.value?.getTableList();
      }, 200);
    });
  } else {
    ElMessage.warning(`未获取到你负责绩效评估的用户，请联系管控组检查权限`);
  }
};
// const batchInit = async () => {
//   let org: any = null;
//   if (proTable.value?.searchParam.orgId) {
//     const curSelectOrgId = proTable.value?.searchParam.orgId;
//     org = orgSelectList.value.find(org => {
//       if (org._id === curSelectOrgId && org.leader === userUser.userInfo._id) {
//         return org;
//       }
//     });
//   } else {
//     ElMessage.warning(`请选择负责组织后操作`);
//     return;
//   }

//   if (org && org._id) {
//     let params = {
//       condition: {
//         orgId: org._id,
//         _id: { $ne: userUser.userInfo._id }
//       },
//       options: { sort: { userName: 1 } }
//     };
//     initParamKey.value = Md5.hashStr(JSON.stringify(params));
//     let data = await dataStore.findList(initParamKey.value, () => apiService.find("users", params.condition, params.options));
//     if (data && data.length > 0) {
//       ElMessageBox.confirm(`你负责的【${org.name}】有【${data.length}条】用户数据，是否导入?`, "温馨提示", {
//         confirmButtonText: "确定",
//         cancelButtonText: "取消",
//         type: "info",
//         draggable: true
//       }).then(() => {
//         data.forEach(async user => {
//           let item: Partial<Performance> = {};

//           let curDate = new Date(proTable.value?.searchParam.performanceDate);
//           let [year, month] = [curDate.getFullYear(), curDate.getMonth()];
//           let defaultDate = new Date(year, month, 1);
//           // 默认上个月
//           item.performanceDate = defaultDate;
//           item.orgId = org._id;
//           item.state = "0";
//           item.create_at = new Date();
//           item.create_user = userUser.userInfo._id;
//           item.chargeUser = userUser.userInfo._id;
//           item.chargeUserName = userUser.userInfo.userName;
//           item.crossGroup = "0";
//           item.crossRate = "1";
//           item.avgScore = 1.0;
//           item.performanceType = "1";
//           item.level = "B";
//           item.chat_state = "0";
//           item.userId = user._id;
//           item.userName = user.userName;
//           await apiService.save(initVar.tbName, item);
//         });
//         ElMessage({
//           type: "success",
//           message: `初始成功!`
//         });
//         proTable.value?.getTableList();
//       });
//     } else {
//       ElMessage.warning(`未获取到你负责的组织用户，请联系管控组检查权限`);
//     }
//   } else {
//     ElMessage.warning(`只能批量初始化负责的组织，其他组织请通过跨组单独新增`);
//   }
// };

const onChatStateChange = async (row: Performance) => {
  if (row && row._id && row.chat_state) {
    await apiService.updateById(initVar.tbName, { _id: row._id, chat_state: row.chat_state });
    ElMessage.success("更新成功");
  }
};

const onScoreChange = async (row: Performance) => {
  if (row && row._id) {
    await apiService.updateById(initVar.tbName, { _id: row._id, avgScore: row.avgScore });
    ElMessage.success("更新成功");
  }
};

const onLevelChange = async (row: Performance) => {
  if (row && row._id && row.level) {
    await apiService.updateById(initVar.tbName, { _id: row._id, level: row.level });
    ElMessage.success("更新成功");
  }
};

// 引入上月绩效评估
const importLastMonth = async () => {
  if (proTable.value?.searchParam.performanceDate) {
    let params: any = {};
    let curDate = new Date(proTable.value?.searchParam.performanceDate);
    let [year, month] = [curDate.getFullYear(), curDate.getMonth()];
    let startDate = new Date(year, month - 1, 1);
    let endDate = new Date(year, month, 0, 23, 59, 59);
    params.performanceDate = { $gte: startDate, $lte: endDate };
    params.chargeUser = userUser.userInfo._id;
    let { data } = await apiService.find<Performance[]>(initVar.tbName, params);
    if (data && data.length > 0) {
      ElMessageBox.confirm(
        `获取到${endDate.getFullYear()}年${endDate.getMonth() + 1}月【${data.length}条】评估数据，是否导入?`,
        "温馨提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "info",
          draggable: true
        }
      ).then(() => {
        data.forEach(async item => {
          delete item._id;
          item.performanceDate = new Date(proTable.value?.searchParam.performanceDate);
          item.state = "0";
          item.create_at = new Date();
          if (item.userId && !checkRepeat(item.userId)) {
            await apiService.save(initVar.tbName, item);
          }
        });
        ElMessage({
          type: "success",
          message: `引入成功!`
        });
        proTable.value?.getTableList();
      });
    } else {
      ElMessage.warning(`未获取到${endDate.getFullYear()}年${endDate.getMonth() + 1}月评估数据`);
    }
  }
};
</script>
